package com.czx.service.impl;

import com.alibaba.fastjson.JSON;
import com.czx.common.constants.RedisKeys;
import com.czx.entity.User;
import com.czx.service.UserTokenService;
import com.czx.common.utils.UUIDUtils;
import com.czx.vo.UserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class UserTokenServiceImpl implements UserTokenService {
    //注入整合第三方框架
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public UserToken createUserToken(User user) {
        //封装userToken对象
        UserToken userToken = new UserToken();
        /*userToken.setUsername(user.getUsername());
        userToken.setUserId(user.getId());
        userToken.setHeaderUrl(user.getHeaderUrl());*/
        userToken.setCreateTime(new Date());
        userToken.setUuid(UUIDUtils.getId());
        userToken.setUser(user);
        //key/value
        //创建工具类
        String key = String.format(RedisKeys.USER_LOGIN_TOKEN_KEY, userToken.getUuid());
        //把userToken对象转换成json字符串
        String value = JSON.toJSONString(userToken);
        //把userToken保存到redis中,设置保存时间
        stringRedisTemplate.opsForValue().set(key, value, 30, TimeUnit.DAYS);
        // 返回userToken给userController
        return userToken;

    }
    // 根据uuid从redis查询userToken
    public UserToken getUserToken(String uuid) {
        String key = String.format(RedisKeys.USER_LOGIN_TOKEN_KEY, uuid);
        String json = stringRedisTemplate.opsForValue().get(key);
        if (!ObjectUtils.isEmpty(json)) {
            return JSON.parseObject(json, UserToken.class);
        }
        return null;
    }
}
